﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace AgileShare.Framework.Library.Common
{
	/// <summary>
	/// 
	/// </summary>
    public static class SPFrameworkExtensions
	{
		/// <summary>
		/// Replaces the XML attribute value.
		/// </summary>
		/// <param name="xml">The XML.</param>
		/// <param name="attributeName">Name of the attribute.</param>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		/// <exception cref="System.ArgumentNullException">xml</exception>
		public static string ReplaceXmlAttributeValue(this string xml, string attributeName, string value)
		{
			if (string.IsNullOrEmpty(xml))
			{
				throw new ArgumentNullException("xml");
			}
			if (string.IsNullOrEmpty(value))
			{
				throw new ArgumentNullException("value");
			}

			XDocument xDoc = XDocument.Parse(xml);
			XElement rootElement = xDoc.Root;

			rootElement.SetAttributeValue(attributeName, value);			

			//int indexOfAttributeName = xml.IndexOf(attributeName, StringComparison.CurrentCultureIgnoreCase);
			//if (indexOfAttributeName != -1)
			//{
			//	int indexOfAttibuteValueBegin = xml.IndexOf('"', indexOfAttributeName);
			//	int indexOfAttributeValueEnd = xml.IndexOf('"', indexOfAttibuteValueBegin + 1);

			//	retVal = xml.Substring(0, indexOfAttibuteValueBegin + 1) + value + xml.Substring(indexOfAttributeValueEnd);
			//}

			return rootElement.ToString();
		}

	}
}
